<template>
  <div class="login-account">
    <el-form label-width="80px" :rules="rules" :model="inputInfo" ref="formRef">
      <el-form-item label="帐号:" prop="name">
        <el-input v-model="inputInfo.name" />
      </el-form-item>
      <el-form-item label="密码:" prop="password">
        <el-input v-model="inputInfo.password" type="password" />
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, ref } from 'vue'
import { useStore } from 'vuex'
import { ElForm } from 'element-plus'
import cache from '@/utils/cache'
export default defineComponent({
  name: 'login-account',
  setup() {
    const userStore = useStore()
    const inputInfo = reactive({
      name: cache.getCache('userInfo')?.name ?? ' ',
      password: cache.getCache('userInfo')?.password ?? ' '
    })
    let rules = {
      name: [
        {
          required: true,
          message: '帐号不能为空',
          trigger: 'blur'
        },
        {
          pattern: /^[a-zA-Z0-9_-]{3,12}$/,
          message: '帐号必须三位以上',
          trigger: 'blur'
        }
      ],
      password: [
        {
          required: true,
          message: '密码不能为空',
          trigger: 'blur'
        }
        // {
        //   pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/,
        //   message: '密码必须包含字母和数字',
        //   trigger: 'blur'
        // }
      ]
    }
    const loginAction = (isSave: boolean) => {
      formRef.value?.validate((isValid) => {
        if (isValid) {
          //判断是否需要保存密码
          if (isSave) {
            cache.setCache('userInfo', inputInfo)
            userStore.dispatch('user/InitiateLogin', inputInfo)
          } else {
            cache.deleteCache('userInfo')
            userStore.dispatch('user/InitiateLogin', inputInfo)
          }
        }
      })
    }
    const formRef = ref<InstanceType<typeof ElForm>>()
    return {
      inputInfo,
      rules,
      loginAction,
      formRef
    }
  }
})
</script>

<style lang="less" scoped></style>
